package user

import (
	"errors"
	"io"
	"net/http"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/tool"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/common"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/excel"

	"gitee.com/liuxuezhan/ar-platform/base-common/result"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userrpc"
	"github.com/zeromicro/go-zero/rest/httpx"
)

// 会员管理 - 会员列表 - 导出
func UserExportHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.UserExportRequest
		if err := httpx.Parse(r, &req); err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}

		rpcReq := &userrpc.UserSearchRequest{
			Id:                req.Id,
			Account:           req.Account,
			RegisterIp:        req.RegisterIp,
			Remark:            req.Remark,
			ChannelCode:       req.ChannelCode,
			RegisterDevice:    req.RegisterDevice,
			Status:            req.Status,
			AgentLevel:        req.AgentLevel,
			InviteCode:        req.InviteCode,
			AmountSort:        req.AmountSort,
			VipLevel:          req.VipLevel,
			RegisterTimeStart: req.RegisterTimeStart,
			RegisterTimeEnd:   req.RegisterTimeEnd,
			OnlineTimeStart:   req.OnlineTimeStart,
			OnlineTimeEnd:     req.OnlineTimeEnd,
			GroupId:           req.GroupId,
			SafeAmountSort:    req.SafeAmountSort,
			Limit:             req.Limit,
		}
		client := svcCtx.UserServiceRPC
		stream, err := client.UserExport(r.Context(), rpcReq)
		if err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}

		excelWriter, err := excel.NewExcelWriter()
		if err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}
		defer excelWriter.Close()

		headers := []string{
			"会员ID",   // id
			"昵称",     // nickname
			"保险箱余额",  // safe_balance
			"会员账号",   // account
			"余额",     // balance
			"积分",     // integral
			"红包剩余金额", // todo
			"邀请码",    // invite_code
			"渠道号",    // channel_code
			"注册IP",   // register_ip
			"注册设备",   // register_device
			"保底量",    // todo
			"分组",     // group_id
			"类型",     // todo
			"黑名单",    // is_blacklist
			"状态",     // status
			"在线状态",   // is_online
			"最后在线",   // last_online_time
			"代理",     // agent_level
			"领取返佣",   // is_pay_back
			"前台谷歌",   // todo
			"后台谷歌",   // todo
			"首次登陆时间", // first_login_time
			"注册时间",   // register_time
			"VIP等级",  // vip_level
			"充值次数",   // recharge_count
			"充值金额",   // recharge_amount
			"首充时间",   // first_charge_time
			"最后充值时间", // last_charge_time
			"备注",     // remark
		}
		excelWriter.SetHeaders(headers)
		index := 2
		for {
			data, err := stream.Recv()
			if errors.Is(err, io.EOF) {
				break
			}
			if err != nil {
				result.HttpErrorResult(r.Context(), w, err)
				return
			}

			excelWriter.AddRow(index, []interface{}{
				data.Id,             // 会员ID
				data.Nickname,       // 昵称
				data.SafeBalance,    // 保险箱余额
				data.Account,        // 会员账号
				data.Balance,        // 余额
				data.Integral,       // 积分
				"-",                 // 红包剩余金额
				data.InviteCode,     // 邀请码
				data.ChannelCode,    // 渠道号
				data.RegisterIp,     // 注册IP
				data.RegisterDevice, // 注册设备
				"-",                 // 保底量 todo
				data.GroupName,      // 分组
				"-",                 // 类型
				common.EnumUserBlacklist[data.IsBlacklist], // 黑名单
				common.EnumUserStatus[data.Status],         // 状态
				common.EnumUserOnline[data.IsOnline],       // 在线状态
				tool.TimeFormat(data.LastOnlineTime, ""),   // 最后在线
				data.AgentLevel,                            // 代理
				data.IsPayBack,                             // 领取返佣
				"-",                                        // 前台谷歌 todo
				"-",                                        // 后台谷歌 todo
				tool.TimeFormat(data.FirstLoginTime, ""),   // 首次登陆时间
				tool.TimeFormat(data.RegisterTime, ""),     // 注册时间
				data.VipLevel,                              // VIP等级
				data.RechargeCount,                         // 充值次数
				data.RechargeAmount,                        // 充值金额
				tool.TimeFormat(data.FirstChargeTime, ""),  // 首充时间
				tool.TimeFormat(data.LastChargeTime, ""),   // 最后充值时间
				data.Remark,                                // 备注
			})
			index++
		}

		excelWriter.Flush()

		// download
		w.Header().Set("Content-Type", "application/octet-stream")
		w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
		excelWriter.Write(w)
	}
}
